package com.awake.auth.controller;

import com.awake.auth.service.ISysUserService;
import com.awake.common.result.Result;
import com.awake.model.system.SysUser;
import com.awake.vo.system.SysUserQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@Api(tags = "用户管理")
@RestController
@RequestMapping("/admin/system/sysUser")
@RequiredArgsConstructor
public class SysUserController {

    private final ISysUserService sysUserService;

    @ApiOperation("用户条件分页查询")
    @GetMapping("/{page}/{limit}")
    public Result<IPage<SysUser>> index(@PathVariable Long page,
                                        @PathVariable Long limit,
                                        SysUserQueryVo sysUserQueryVo) {
        // 创建page对象
        Page<SysUser> pageParam = new Page<>(page, limit);

        // 封装条件，判断条件值不为空
        LambdaQueryWrapper<SysUser> wrapper = Wrappers.lambdaQuery();
        // 获取条件值
        wrapper.like(!StringUtils.isEmpty(sysUserQueryVo.getKeyword()), SysUser::getUsername, sysUserQueryVo.getKeyword())
                .ge(!StringUtils.isEmpty(sysUserQueryVo.getCreateTimeBegin()), SysUser::getCreateTime, sysUserQueryVo.getCreateTimeBegin())
                .le(!StringUtils.isEmpty(sysUserQueryVo.getCreateTimeEnd()), SysUser::getCreateTime, sysUserQueryVo.getCreateTimeEnd());
        // 调用mp的方法实现条件分页查询
        IPage<SysUser> pageModel = sysUserService.page(pageParam, wrapper);
        return Result.ok(pageModel);
    }

    @ApiOperation(value = "获取用户")
    @GetMapping("/get/{id}")
    public Result<SysUser> get(@PathVariable Long id) {
        SysUser user = sysUserService.getById(id);
        return Result.ok(user);
    }

    @ApiOperation(value = "保存用户")
    @PostMapping("/save")
    public Result<Void> save(@RequestBody SysUser user) {
        sysUserService.save(user);
        return Result.ok();
    }

    @ApiOperation(value = "更新用户")
    @PutMapping("/update")
    public Result<Void> updateById(@RequestBody SysUser user) {
        sysUserService.updateById(user);
        return Result.ok();
    }

    @ApiOperation(value = "删除用户")
    @DeleteMapping("/remove/{id}")
    public Result<Void> remove(@PathVariable Long id) {
        sysUserService.removeById(id);
        return Result.ok();
    }

    @ApiOperation(value = "更新状态")
    @GetMapping("updateStatus/{id}/{status}")
    public Result<Void> updateStatus(@PathVariable Long id, @PathVariable Integer status) {
        sysUserService.updateStatus(id, status);
        return Result.ok();
    }
}
